<template>
    <div class="search-page">

    <!-- 筛选条件 -->
    <div class="filter-section">
      <div class="container">
        <el-row>
          <el-col :span="2">
            <span>尺码</span>
          </el-col>
          <el-col :span="22">
            <div class="filter-options">
            <el-button
              v-for="size in sizeOptions"
              :key="size"
              :type="selectedSizes.includes(size) ? 'warning' : 'default'"
              size="small"
              plain
              @click="toggleSize(size)"
            >
              {{ size }}
            </el-button>
            </div>
          </el-col>
        </el-row>


        <!-- 颜色筛选 -->
         <el-row style="margin-top: 15px;">
          <el-col :span="2">
            <span>颜色</span>
          </el-col>
          <el-col :span="22">
            <div class="filter-options">
            <el-button
              v-for="color in colorOptions"
              :key="color"
              :type="selectedColors.includes(color) ? 'warning' : 'default'"
              size="small"
              plain
              @click="toggleColor(color)"
            >
              {{ color }}
            </el-button>
            </div>
          </el-col>
        </el-row>

        <!-- 品牌筛选 -->
         <el-row style="margin-top: 15px;">
          <el-col :span="2">
            <span>品牌</span>
          </el-col>
          <el-col :span="22">
            <div class="filter-options">
            <el-button
              v-for="brand in brandOptions"
              :key="brand"
              :type="selectedBrands.includes(brand) ? 'warning' : 'default'"
              size="small"
              plain
              @click="toggleBrand(brand)"
            >
              {{ brand }}
            </el-button>
            </div>
          </el-col>
        </el-row>

        <!-- 价格筛选 -->
        <el-row style="margin-top: 15px;">
          <el-col :span="2">
            <span>价格</span>
          </el-col>
          <el-col :span="22">
            <div class="filter-options">
            <el-button
              v-for="price in priceOptions"
              :key="price"
              :type="selectedPrices.includes(price) ? 'warning' : 'default'"
              size="small"
              plain
              @click="togglePrice(price)"
            >
              {{ price }}
            </el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="products-section">
      <div class="container">
        <div class="products-grid">
          <div
            v-for="product in filteredProducts"
            :key="product.id"
            class="product-card"
            @click="goToProduct(product.id)"
          >
            <div class="product-image">
              <img :src="product.image" :alt="product.name" />
            </div>
            <div class="product-info">
              <h3 class="product-name">{{ product.name }}</h3>
              <div class="product-details">
                <span class="product-color">颜色：{{ product.color }}</span>
                <span class="product-brand"> 品牌：{{ product.brand }}</span>
              </div>
              <div class="product-price">
                <span class="current-price">¥ {{ product.price }}</span>
                <span v-if="product.originalPrice" class="original-price">¥ {{ product.originalPrice }}</span>
              </div>
              <div class="product-rating">
                <el-rate v-model="product.rating" disabled size="small" />
                <span class="rating-text">{{ product.rating }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="totalProducts"
            layout="prev, pager, next"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>

    <!-- 底部服务保障 -->
    <div class="service-section">
      <div class="container">
        <div class="service-items">
          <div class="service-item">
            <el-icon class="service-icon"><CircleCheck /></el-icon>
            <span>正品保障</span>
          </div>
          <div class="service-item">
            <el-icon class="service-icon"><Clock /></el-icon>
            <span>7天无理由退货</span>
          </div>
          <div class="service-item">
            <el-icon class="service-icon"><Van /></el-icon>
            <span>15天免费换货</span>
          </div>
          <div class="service-item">
            <el-icon class="service-icon"><Coin /></el-icon>
            <span>满69元包邮</span>
          </div>
          <div class="service-item">
            <el-icon class="service-icon"><Lightning /></el-icon>
            <span>闪电发货</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import {
  Search,
  ShoppingCart,
  View,
  CircleCheck,
  Clock,
  Van,
  Coin,
  Lightning
} from '@element-plus/icons-vue'
import { searchProducts } from '@/api/product'
import { findAllProductsBrands } from '@/api/product'
import { findNewProducts } from '@/api/product'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

// 获取所有品牌列表
const fetchAllBrands = () => {
  // 防止重复加载
  if (isBrandsLoading.value) {
    console.log('品牌数据正在加载中，跳过重复请求')
    return
  }
  
  isBrandsLoading.value = true
  console.log('开始获取品牌数据...')
  
  findAllProductsBrands().then(res => {
    console.log('品牌API返回数据:', res)
    // 确保res.data存在且是数组
    if (Array.isArray(res.data)) {
      const brands = res.data.map(item => item.name || '未知品牌')
      console.log('原始品牌数据:', brands)
      // 去重处理
      brandOptions.value = [...new Set(brands)]
      console.log('去重后的品牌列表:', brandOptions.value)
      console.log('品牌数量统计:', 
        brands.reduce((acc, brand) => {
          acc[brand] = (acc[brand] || 0) + 1
          return acc
        }, {})
      )
    } else {
      console.warn('品牌数据格式不正确:', res.data)
    }
  }).catch(error => {
    console.error('获取品牌列表失败:', error)
    // 设置一些默认品牌选项，避免空白
    brandOptions.value = ['耐克', '阿迪达斯', '李宁', '安踏', '新百伦']
  }).finally(() => {
    isBrandsLoading.value = false
    console.log('品牌数据加载完成')
  })
}
const SearchProducts = () => {
  // 显示加载状态（如果需要）
  // loading.value = true
  
  searchProducts({
    keyword: searchKeyword.value,
  }).then(res => {
    products.value = res.data || []
    currentPage.value = 1 // 搜索后重置到第一页
    
    // 如果没有搜索结果，可以显示提示信息
    if (products.value.length === 0) {
      // 可以添加无结果的提示逻辑
      console.log('没有找到匹配的商品')
    } else {
      // 调试：显示第一个商品的结构
      console.log('搜索到的商品数据示例:', products.value[0])
      console.log('商品属性:', Object.keys(products.value[0]))
    }
  }).catch(error => {
    console.error('搜索失败:', error)
    // 可以添加错误提示逻辑
  }).finally(() => {
    // 隐藏加载状态
    // loading.value = false
  })
}

// 处理新品上市搜索
const SearchNewProducts = () => {
  findNewProducts().then(res => {
    products.value = res.data || []
    currentPage.value = 1 // 搜索后重置到第一页
    
    // 如果没有搜索结果，可以显示提示信息
    if (products.value.length === 0) {
      console.log('没有找到新品商品')
    } else {
      // 调试：显示第一个商品的结构
      console.log('新品商品数据示例:', products.value[0])
      console.log('商品属性:', Object.keys(products.value[0]))
    }
  }).catch(error => {
    console.error('获取新品失败:', error)
  })
}

// 处理特价促销搜索
const SearchSaleProducts = () => {
  searchProducts({
    isOnSale: true,
  }).then(res => {
    products.value = res.data || []
    currentPage.value = 1 // 搜索后重置到第一页
    
    // 如果没有搜索结果，可以显示提示信息
    if (products.value.length === 0) {
      console.log('没有找到特价商品')
    } else {
      // 调试：显示第一个商品的结构
      console.log('特价商品数据示例:', products.value[0])
      console.log('商品属性:', Object.keys(products.value[0]))
    }
  }).catch(error => {
    console.error('获取特价商品失败:', error)
  })
}
const searchKeyword = ref('')
const cartCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 从URL参数中获取搜索参数
const getParamsFromUrl = () => {
  const urlParams = new URLSearchParams(window.location.search)
  const keyword = urlParams.get('keyword')
  const type = urlParams.get('type')
  const isOnSale = urlParams.get('isOnSale')
  
  if (keyword) {
    searchKeyword.value = decodeURIComponent(keyword)
    // 执行关键词搜索
    SearchProducts()
  } else if (type === 'new') {
    // 新品上市
    SearchNewProducts()
  } else if (type === 'sale' || isOnSale === 'true') {
    // 特价促销
    SearchSaleProducts()
  } else {
    // 没有特定参数时（如点击"全部商品"），显示所有商品
    console.log('没有搜索参数，显示所有商品')
    SearchProducts() // 调用搜索函数，但不传关键词，显示所有商品
  }
}

// 页面加载时获取URL参数和执行搜索
onMounted(() => {
  getParamsFromUrl() // 这个函数内部会根据参数类型调用相应的搜索函数
  // 只在品牌选项为空时加载品牌数据，避免重复加载
  if (brandOptions.value.length === 0) {
    fetchAllBrands() // 使用重命名后的函数
  }
})

// 监听路由参数变化
watch(() => route.query, (newQuery) => {
  if (newQuery.keyword && newQuery.keyword !== searchKeyword.value) {
    searchKeyword.value = decodeURIComponent(newQuery.keyword)
    SearchProducts()
  } else if (newQuery.type === 'new') {
    SearchNewProducts()
  } else if (newQuery.type === 'sale' || newQuery.isOnSale === 'true') {
    SearchSaleProducts()
  } else if (!newQuery.keyword && !newQuery.type && !newQuery.isOnSale) {
    // 当没有任何查询参数时（如点击"全部商品"），显示所有商品
    console.log('路由参数清空，显示所有商品')
    searchKeyword.value = '' // 清空搜索关键词
    SearchProducts() // 显示所有商品
  }
}, { immediate: true, deep: true })
// 筛选条件
const selectedSizes = ref([])
const selectedColors = ref([])
const selectedBrands = ref([])
const selectedPrices = ref([])
const products = ref([])
// 筛选选项
const sizeOptions = ref([36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 10, 11, 12])
const colorOptions = ref(['白色', '黑色', '蓝色', '红色', '绿色', '黄色', '灰色', '棕色', '紫色', '粉色', '橙色', '多色'])
const brandOptions = ref([

])
const isBrandsLoading = ref(false) // 防止重复加载品牌数据
const priceOptions = ref(['0-99', '100-299', '300-499', '500-799', '800-1299', '1300以上'])
// 跳转商品详情
const goToProduct = (productId) => {
  router.push({ 
    path: "/product/detail",
    query: {productId}
   })
}
// 过滤后的商品
const filteredProducts = computed(() => {
  console.log('开始筛选，商品总数:', products.value.length)
  console.log('选中尺码:', selectedSizes.value)
  console.log('选中颜色:', selectedColors.value)
  console.log('选中品牌:', selectedBrands.value)
  console.log('选中价格:', selectedPrices.value)
  
  let filtered = products.value

  // 尺码筛选
  if (selectedSizes.value.length > 0) {
    filtered = filtered.filter(product => {
      if (!product.sizes || !Array.isArray(product.sizes)) return false
      return product.sizes.some(sizeObj => {
        // 兼容不同数据结构
        const sizeValue = sizeObj.sizeValue || sizeObj.size || sizeObj
        return selectedSizes.value.includes(parseFloat(sizeValue))
      })
    })
  }

  // 颜色筛选
  if (selectedColors.value.length > 0) {
    filtered = filtered.filter(product => {
      const productColor = product.colorName || product.color
      return productColor && selectedColors.value.includes(productColor)
    })
  }

  // 品牌筛选
  if (selectedBrands.value.length > 0) {
    filtered = filtered.filter(product => {
      const productBrand = product.brandName || product.brand
      return productBrand && selectedBrands.value.includes(productBrand)
    })
  }

  // 价格筛选
  if (selectedPrices.value.length > 0) {
    filtered = filtered.filter(product => {
      return selectedPrices.value.some(priceRange => {
        if (priceRange === '0-99') return product.price <= 99
        if (priceRange === '100-299') return product.price >= 100 && product.price <= 299
        if (priceRange === '300-499') return product.price >= 300 && product.price <= 499
        if (priceRange === '500-799') return product.price >= 500 && product.price <= 799
        if (priceRange === '800-1299') return product.price >= 800 && product.price <= 1299
        if (priceRange === '1300以上') return product.price >= 1300
        return false
      })
    })
  }

  console.log('筛选完成，结果数量:', filtered.length)
  return filtered
})

const totalProducts = computed(() => filteredProducts.value.length)

// 筛选方法
const toggleSize = (size) => {
  console.log('切换尺码:', size)
  const index = selectedSizes.value.indexOf(size)
  if (index > -1) {
    selectedSizes.value.splice(index, 1)
    console.log('移除尺码:', size, '当前选中尺码:', selectedSizes.value)
  } else {
    selectedSizes.value.push(size)
    console.log('添加尺码:', size, '当前选中尺码:', selectedSizes.value)
  }
}

const toggleColor = (color) => {
  console.log('切换颜色:', color)
  const index = selectedColors.value.indexOf(color)
  if (index > -1) {
    selectedColors.value.splice(index, 1)
    console.log('移除颜色:', color, '当前选中颜色:', selectedColors.value)
  } else {
    selectedColors.value.push(color)
    console.log('添加颜色:', color, '当前选中颜色:', selectedColors.value)
  }
}

const toggleBrand = (brand) => {
  console.log('切换品牌:', brand)
  const index = selectedBrands.value.indexOf(brand)
  if (index > -1) {
    selectedBrands.value.splice(index, 1)
    console.log('移除品牌:', brand, '当前选中品牌:', selectedBrands.value)
  } else {
    selectedBrands.value.push(brand)
    console.log('添加品牌:', brand, '当前选中品牌:', selectedBrands.value)
  }
}

const togglePrice = (price) => {
  console.log('切换价格:', price)
  const index = selectedPrices.value.indexOf(price)
  if (index > -1) {
    selectedPrices.value.splice(index, 1)
    console.log('移除价格:', price, '当前选中价格:', selectedPrices.value)
  } else {
    selectedPrices.value.push(price)
    console.log('添加价格:', price, '当前选中价格:', selectedPrices.value)
  }
}



// 分页方法
const handlePageChange = (page) => {
  currentPage.value = page
}


</script>

<style scoped>
.search-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

/* Header */
.header {
  background: linear-gradient(135deg, #ff8c00 0%, #ffa500 100%);
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 0;
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.brand-name {
  font-size: 20px;
  font-weight: bold;
  color: white;
}

.search-bar {
  flex: 1;
  max-width: 500px;
  margin: 0 30px;
}

.user-actions {
  display: flex;
  align-items: center;
  gap: 15px;
  color: white;
}

.user-info {
  font-size: 14px;
}

.logout-btn {
  color: white !important;
}

.cart-btn {
  background-color: rgba(255,255,255,0.2);
  border-color: rgba(255,255,255,0.3);
  color: white;
}

/* Breadcrumb */
.breadcrumb-section {
  background: white;
  padding: 15px 0;
  border-bottom: 1px solid #e0e0e0;
}

/* Filter Section */
.filter-section {
  background: white;
  padding: 20px 0;
  border-bottom: 1px solid #e0e0e0;
}

.filter-group {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.filter-group:last-child {
  margin-bottom: 0;
}

.filter-label {
  width: 80px;
  font-weight: 500;
  color: #333;
  margin-right: 20px;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* Products Section */
.products-section {
  background: white;
  padding: 30px 0;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 24px;
  margin-bottom: 40px;
}

.product-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transition: all 0.3s;
  cursor: pointer;
  border: 1px solid #e0e0e0;
}

.product-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0,0,0,0.15);
}

.product-image {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  background-color: #f0f0f0;
}

.product-actions {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.product-card:hover .product-actions {
  opacity: 1;
}

.product-info {
  padding: 16px;
}

.product-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-price {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.current-price {
  font-size: 16px;
  font-weight: bold;
  color: #e74c3c;
}

.original-price {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
}

.product-rating {
  display: flex;
  align-items: center;
  gap: 8px;
}

.rating-text {
  font-size: 12px;
  color: #666;
}

/* Pagination */
.pagination-section {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

/* Service Section */
.service-section {
  background: #f8f9fa;
  padding: 30px 0;
  border-top: 1px solid #e0e0e0;
}

.service-items {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.service-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #666;
}

.service-icon {
  font-size: 24px;
  color: #ff8c00;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 15px;
  }

  .search-bar {
    width: 100%;
    margin: 0;
  }

  .filter-group {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .filter-label {
    width: auto;
    margin-right: 0;
  }

  .products-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 16px;
  }

  .service-items {
    flex-direction: column;
    gap: 20px;
  }
}

:deep(.el-button--warning.is-plain) {
  background-color: #ff8c00;
  border-color: #ff8c00;
  color: white;
}

:deep(.el-button--warning.is-plain:hover) {
  background-color: #e67e00;
  border-color: #e67e00;
  color: white;
}
</style>